<template>
  <div id="Login">
      <div class="profile ">
        <img src="https://img0.baidu.com/it/u=598508349,1160993736&fm=26&fmt=auto" alt="">
      </div>
      <div class="form">
        <el-form :model="ruleForm" ref="ruleForm" status-icon :rules="rules" label-width="0px" class="demo-ruleForm">

  <el-form-item prop="username">
    <el-input v-model="ruleForm.username" prefix-icon="el-icon-s-custom"></el-input>
  </el-form-item>

  <el-form-item prop="password">
    <el-input type="password" v-model="ruleForm.password" prefix-icon="el-icon-view"></el-input>
  </el-form-item>

  <el-form-item class="btn">
    <el-button type='primary' @click="login('ruleForm')">登录</el-button>
    <el-button type='info' @click="resetForm('ruleForm')">重置</el-button>
  </el-form-item>
</el-form>
      </div>
  </div>
</template>

<script>
export default {
  data(){
    return{
      ruleForm:{
        username:'',
        password:'',
      },
      rules:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ]
        }
    }
  },
  methods:{
    login(formName){
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const {data:res}=await this.$http.post('login',this.ruleForm)
            if(res.meta.status === 400){
              this.$message.error('登录失败');
            }else{
              this.$message({
                message: '登录成功',
                type: 'success'
            });
            window.localStorage.setItem('token',res.data.token)
            this.$router.push('/home')
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    // 表单重置
    resetForm(formName) {
        this.$refs[formName].resetFields();
    },
  }
}
</script>

<style lang="less" scoped>
#Login{
  position: relative;
  background-color: #fff;
  height: 300px;
  width: 450px;
  position: absolute; 
  left: 50%; 
  top: 50%;   
  transform: translate(-50%, -50%);
  .profile{
    position: absolute;
    left: 50%;
    top: 0;
    margin-left: -60px;
    margin-top: -60px;
    img{
      width: 120px;
      height: 120px;
      border-radius: 50%;
    }
  }
  .form{
    margin-top: 120px;
    padding: 0 20px;
   .btn{
     display: flex;
     justify-content: flex-end;
   }
  }
}
</style>